﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Speech.AudioFormat;
using System.Speech.Synthesis;
using System.Threading.Tasks;
using System.IO;

namespace TTSTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TextToSpeechController : ControllerBase
    {
        private readonly IWebHostEnvironment _hostingEnvironment;

        public TextToSpeechController(IWebHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpGet]
        public ActionResult<string> get(string text)
        {
            try
            {
                if (text.Length > 65535)
                {
                    return new JsonResult(new { code = 1, msg = "文字长度太长了，请将文字控制在65535个字符之内！", url = "" });
                }
                string fileName = GetMD5(text);
                string filePath = _hostingEnvironment.ContentRootPath + $"\\wwwroot\\speech\\{fileName}.wav";
                if (System.IO.File.Exists(filePath))
                {
                    return new JsonResult(new { code = 0, msg = "语音存在了！", url = $"/speech/{fileName}.wav" });
                }
                else
                {
                    using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    {
                        synth.SetOutputToWaveFile(filePath, new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
                        PromptBuilder builder = new PromptBuilder();
                        builder.AppendText(text);
                        synth.Speak(builder);
                    }
                    return new JsonResult(new { code = 0, msg = "生成语音成功！", url = $"/speech/{fileName}.wav" });
                }
            }
            catch (Exception e)
            {
                return new JsonResult(new { code = -1, msg = "生成语音失败了！", url = e });
            }

        }

        private string GetMD5(string myString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;
            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }
            return byte2String;
        }
    }
}
